using CCWin;
using ProcessMonitor.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace ProcessMonitor
{
    public partial class FrmMain : Skin_Color
    {
        /// <summary>
        /// 选中的一行数据
        /// </summary>
        private string selectKid = "";
        public WinProcess winpro = new WinProcess();
        /// <summary>
        /// 未开启监测
        /// </summary>
        private Color NotMonitorBg = Color.LightGray;

        /// <summary>
        /// 开启监测 未运行
        /// </summary>
        private Color NotRunBg = Color.Red;

        /// <summary>
        /// 开启监测且成功运行
        /// </summary>
        private Color SuccessBg = Color.White;


        public FrmMain()
        {
            InitializeComponent();

            this.Text = this.Text + " " + ProcessData.VesinNo;

            SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
            UpdateStyles();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ProLogic.Instance.EventUpdateResultAnalysis += ProLogic_EventUpdateResultAnalysis;
            ProLogic.Instance.LoadXmlConfig();
            ShowXmlToListView();

            new QuartzWork().Start();

            var isAutoStart = SystemHelper.IsAutoRun();
            if (isAutoStart)
            {
                this.开机启动监控ToolStripMenuItem.Image = global::ProcessMonitor.Properties.Resources.png_0044;
                this.关闭开启启动ToolStripMenuItem.Image = null;
            }
            else
            {
                this.开机启动监控ToolStripMenuItem.Image = null;
                this.关闭开启启动ToolStripMenuItem.Image = global::ProcessMonitor.Properties.Resources.png_0044;
            }
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void ShowXmlToListView()
        {
            listView1.Items.Clear();
            foreach (var item in ProcessData.processlist)
            {
                ListViewItem li = new ListViewItem(item.kid);
                if (!item.IsRestart)
                {
                    li.BackColor = NotMonitorBg;
                }
                else if (item.IsDie)
                {
                    li.BackColor = NotRunBg;
                }
                else
                {
                    li.BackColor = SuccessBg;
                }
                li.SubItems.Add(item.IndexNum.ToString());
                li.SubItems.Add(item.PID);
                li.SubItems.Add(item.Desc);
                li.SubItems.Add(item.Name);
                li.SubItems.Add(item.Path);
                li.SubItems.Add(item.StartTime);
                li.SubItems.Add(item.IsRestart ? "启用" : "禁用");
                li.SubItems.Add(item.IsDie ? "未运行" : "运行中");
                li.SubItems.Add(item.Info);
                li.SubItems.Add(item.AutoReboot);
                li.SubItems.Add(item.RebootTimeSet);
                li.SubItems.Add(item.RestartTime);
                listView1.Items.Add(li);
            }
        }


        /// <summary>
        /// 修改委托事件
        /// </summary>
        /// <param name="proidx"></param>
        private void ProLogic_EventUpdateResultAnalysis(int proidx)
        {
            try
            {
                var pro = ProcessData.processlist.FirstOrDefault(p => p.IndexNum == proidx);
                if (proidx == 99999)
                {
                    pro = ProcessData.processlist.LastOrDefault();
                }
                if (pro == null)
                {
                    listView1.Items.RemoveAt(proidx);
                    for (int i = proidx; i < listView1.Items.Count; i++)
                    {
                        listView1.Items[i].SubItems[1].Text = (Convert.ToInt32(listView1.Items[i].SubItems[1].Text) - 1).ToString();
                    }
                }
                else
                {
                    this.Invoke(new Action(() =>
                    {
                        if (proidx < 99999)
                        {
                            if (!pro.IsRestart)
                            {
                                listView1.Items[proidx].BackColor = NotMonitorBg;
                            }
                            else if (pro.IsDie)
                            {
                                listView1.Items[proidx].BackColor = NotRunBg;
                            }
                            else
                            {
                                listView1.Items[proidx].BackColor = SuccessBg;
                            }
                            listView1.Items[proidx].SubItems[2].Text = pro.PID;
                            listView1.Items[proidx].SubItems[3].Text = pro.Desc;
                            listView1.Items[proidx].SubItems[4].Text = pro.Name;
                            listView1.Items[proidx].SubItems[5].Text = pro.Path;
                            listView1.Items[proidx].SubItems[6].Text = pro.StartTime;
                            listView1.Items[proidx].SubItems[7].Text = pro.IsRestart ? "启用" : "禁用";
                            listView1.Items[proidx].SubItems[8].Text = pro.IsDie ? "未运行" : "运行中";
                            listView1.Items[proidx].SubItems[9].Text = pro.Info;
                            listView1.Items[proidx].SubItems[10].Text = pro.AutoReboot;
                            listView1.Items[proidx].SubItems[11].Text = pro.RebootTimeSet;
                            listView1.Items[proidx].SubItems[12].Text = pro.RestartTime;
                        }
                        else
                        {
                            ListViewItem li = new ListViewItem(pro.kid);
                            if (!pro.IsRestart)
                            {
                                li.BackColor = NotMonitorBg;
                            }
                            else if (pro.IsDie)
                            {
                                li.BackColor = NotRunBg;
                            }
                            else
                            {
                                li.BackColor = SuccessBg;
                            }
                            li.SubItems.Add(pro.IndexNum.ToString());
                            li.SubItems.Add(pro.PID);
                            li.SubItems.Add(pro.Desc);
                            li.SubItems.Add(pro.Name);
                            li.SubItems.Add(pro.Path);
                            li.SubItems.Add(pro.StartTime);
                            li.SubItems.Add(pro.IsRestart ? "启用" : "禁用");
                            li.SubItems.Add(pro.IsDie ? "未运行" : "运行中");
                            li.SubItems.Add(pro.Info);
                            li.SubItems.Add(pro.AutoReboot);
                            li.SubItems.Add(pro.RebootTimeSet);
                            li.SubItems.Add(pro.RestartTime);
                            listView1.Items.Add(li);
                        }

                    }));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        /// <summary>
        /// 添加进程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mbtnadd_Click(object sender, EventArgs e)
        {
            FrmAdd add = new FrmAdd(null);
            add.ShowDialog();
        }

        private void 编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(selectKid))
            {
                MessageBox.Show("请先选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var first = ProcessData.processlist.FirstOrDefault(p => p.IndexNum.ToString() == selectKid);
            if (first != null)
            {
                FrmAdd add = new FrmAdd(first);
                add.ShowDialog();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0) return;
            else
            {
                selectKid = listView1.SelectedItems[0].SubItems[1].Text;
            }
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProLogic.Instance.LoadXmlConfig();

            ShowXmlToListView();
        }

        private void mbtnStop_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(selectKid))
            {
                MessageBox.Show("请先选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show("禁用后将不再对其监控，确认禁用吗？", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                ProLogic.Instance.StartOrStopMonitor(Convert.ToInt32(selectKid), false);
            }
        }

        private void mbtnStart_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(selectKid))
            {
                MessageBox.Show("请先选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var pro = ProcessData.processlist.FirstOrDefault(p => p.IndexNum.ToString() == selectKid);
            if (!Directory.Exists(pro.Path))
            {
                MessageBox.Show("目录不存在，无法重启。");
                return;
            }

            ProLogic.Instance.StartOrStopMonitor(Convert.ToInt32(selectKid), true);
        }

        private void mbtnDel_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(selectKid))
            {
                MessageBox.Show("请先选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show($"删除后不可恢复且不再对其监控，\r\n确认删除【{listView1.Items[Convert.ToInt32(selectKid)].SubItems[3].Text}】吗？", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                ProLogic.Instance.DelPro(Convert.ToInt32(selectKid));
            }
        }

        private void 说明ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmHelp frm = new FrmHelp();
            frm.ShowDialog();
        }

        /// <summary>
        /// 双击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (listView1.SelectedItems.Count == 0) return;
            else
            {
                selectKid = listView1.SelectedItems[0].SubItems[1].Text;
            }
            var first = ProcessData.processlist.FirstOrDefault(p => p.IndexNum.ToString() == selectKid);
            if (first != null)
            {
                FrmAdd add = new FrmAdd(first);
                add.ShowDialog();
            }
        }

        private void 重启进程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(selectKid))
            {
                MessageBox.Show("请先选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var pro = ProcessData.processlist.FirstOrDefault(p => p.IndexNum.ToString() == selectKid);
            if (!Directory.Exists(pro.Path))
            {
                MessageBox.Show("目录不存在，请核对重试");
                return;
            }
            if (MessageBox.Show($"确认重启【{pro.Desc}】进程吗？", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var findpro = Process.GetProcessesByName(pro.Name.Split(' ')[0].Replace(".exe", "")).FirstOrDefault(p => p.MainModule.FileName == pro.Path + Path.DirectorySeparatorChar + pro.Name.Split(' ')[0]);
                if (findpro != null && findpro.Id > 0)
                {
                    findpro.Kill();
                    ProcessData.processlist[pro.IndexNum].PID = "0";
                    ProcessData.processlist[pro.IndexNum].IsDie = true;
                    ProcessData.processlist[pro.IndexNum].Info = "重启...";
                    ProLogic_EventUpdateResultAnalysis(pro.IndexNum);
                    Thread.Sleep(200);
                }
                if (File.Exists(pro.Path + Path.DirectorySeparatorChar + pro.Name.Split(' ')[0]))
                {
                    winpro.SetForm(pro.Path + Path.DirectorySeparatorChar + pro.Name);
                    Thread.Sleep(200);
                    findpro = Process.GetProcessesByName(pro.Name.Split(' ')[0].Replace(".exe", "")).FirstOrDefault(p => p.MainModule.FileName == pro.Path + Path.DirectorySeparatorChar + pro.Name.Split(' ')[0]);
                    ProcessData.processlist[pro.IndexNum].PID = findpro?.Id.ToString();
                    ProcessData.processlist[pro.IndexNum].IsDie = findpro == null;
                    ProcessData.processlist[pro.IndexNum].Info = "-";
                    ProcessData.processlist[pro.IndexNum].RestartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    ProLogic.Instance.SycnUpdateReStartTimeToXml(pro.IndexNum, ProcessData.processlist[pro.IndexNum].RestartTime);
                    ProLogic_EventUpdateResultAnalysis(pro.IndexNum);
                }
            }
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("确认退出吗？退出后不再监控配置进程，不影响已启动进程。", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                e.Cancel = false;  //点击OK
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 结束进程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(selectKid))
            {
                MessageBox.Show("请先选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var pro = ProcessData.processlist.FirstOrDefault(p => p.IndexNum.ToString() == selectKid);

            if (MessageBox.Show($"确认结束【{pro.Desc}】进程吗？", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var findpro = Process.GetProcessesByName(pro.Name.Split(' ')[0].Replace(".exe", "")).FirstOrDefault(p => p.MainModule.FileName == pro.Path + Path.DirectorySeparatorChar + pro.Name.Split(' ')[0]);
                if (findpro != null && findpro.Id > 0)
                {
                    findpro.Kill();
                    ProcessData.processlist[pro.IndexNum].PID = "0";
                    ProcessData.processlist[pro.IndexNum].IsDie = true;
                    ProcessData.processlist[pro.IndexNum].Info = "手动结束";
                    ProLogic_EventUpdateResultAnalysis(pro.IndexNum);
                }
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(selectKid))
            {
                MessageBox.Show("请先选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var pro = ProcessData.processlist.FirstOrDefault(p => p.IndexNum.ToString() == selectKid);
            if (Directory.Exists(pro.Path))
            {
                System.Diagnostics.Process.Start("Explorer", pro.Path);
            }
            else
            {
                MessageBox.Show("目录不存在，请核对重试");
            }
        }

        private void 转到进程ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(selectKid))
            {
                MessageBox.Show("请先选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var pro = ProcessData.processlist.FirstOrDefault(p => p.IndexNum.ToString() == selectKid);
            if (!Directory.Exists(pro.Path))
            {
                MessageBox.Show("目录不存在，请核对重试");
                return;
            }

            if (!pro.IsDie)
            {
                winpro.SetForm(pro.Path + Path.DirectorySeparatorChar + pro.Name);
            }
            else
            {
                MessageBox.Show("进程未启动或未纳入监控，请稍候再试。");
            }
        }


        private void 开机启动监控ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strFilePath = Application.ExecutablePath;
            string strFileName = System.IO.Path.GetFileName(strFilePath);

            var res = SystemHelper.SetAutoRun(strFilePath, strFileName, true);
            var isOk = SystemHelper.IsAutoRun();
            if (isOk)
            {
                MessageBox.Show("设置开机启动成功，请以实际验证结果为准", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.开机启动监控ToolStripMenuItem.Image = global::ProcessMonitor.Properties.Resources.png_0044;
                this.关闭开启启动ToolStripMenuItem.Image = null;
            }
            else
            {
                MessageBox.Show(res, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void 关闭开启启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strFilePath = Application.ExecutablePath;
            string strFileName = System.IO.Path.GetFileName(strFilePath);

            var res = SystemHelper.SetAutoRun(strFilePath, strFileName, false);

            var isOk = SystemHelper.IsAutoRun();
            if (!isOk)
            {
                MessageBox.Show("取消开机启动成功，请以实际验证结果为准", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.开机启动监控ToolStripMenuItem.Image = null;
                this.关闭开启启动ToolStripMenuItem.Image = global::ProcessMonitor.Properties.Resources.png_0044;
            }
            else
            {
                MessageBox.Show(res, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    //public class DoubleBufferListView : ListView
    //{
    //    public DoubleBufferListView()
    //    {
    //        SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
    //        UpdateStyles();
    //    }
    //}
}
